package com.example.tongyao.system.service;

import com.example.tongyao.system.entity.SysUser;
import com.example.tongyao.utils.token.UserUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 动态权限类
 *
 * @version 2.0
 * @author tongyao
 * @since 2021-08-04
 */
@Component("SecurityPermission")
public class SecurityPermissionService implements SecurityPermission {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Resource
    private ISysRoleAuthService iSysRoleAuthService;

    @Override
    public boolean addPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;
        if (principal instanceof UserDetails) { //首先判断先当前用户是否是我们UserDetails对象。

            String roleId = ((SysUser)UserUtils.getUserInfo()).getRoleId();

            Set<String> urls = new HashSet<>();
            List<String> urlList =  iSysRoleAuthService.getAuthMenuInterfaceAddressByRoleId(roleId);
            for (String authUrl: urlList) {
                urls.add(authUrl);
            }
            // 注意这里不能用equal来判断，因为有些URL是有参数的，所以要用AntPathMatcher来比较
            for (String url : urls) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
        }
        return hasPermission;
    }
}